import { Injectable } from '@angular/core';
import { DropdownConfig, CheckboxConfig } from '../utils/component-config';
import { of } from 'rxjs/internal/observable/of';
import { AppSetting } from './zone.service';
import { ConfigMetaBase } from '../utils/config-meta-base';

@Injectable({
  providedIn: 'root',
})
export class ConfigMetaService {
  constructor() {}

  getDropDownConfig(meta: AppSetting): ConfigMetaBase<number> {
    const optionStrs = meta.options.split(',');
    const options = optionStrs.map((str, index) => {
      return {
        value: Math.abs(index - 1),
        text: str,
      };
    });

    return new DropdownConfig({
      key: meta.en_name.trim(),
      label: meta.cn_name,
      options: options,
      order: meta.display_order,
      controlType: 'dropdown',
      group_name: meta.group_name,
      tips: meta.tool_tip,
      value: meta.whether_enable,
      relation: meta.relations_keys,
    });
  }

  getCheckboxConfig(meta: AppSetting): ConfigMetaBase<number> {
    const optionStrs = meta.options.split(',');
    const options = optionStrs.map((str, index) => {
      return {
        value: Math.abs(index - 1),
        text: str,
      };
    });
    return new CheckboxConfig({
      key: meta.en_name.trim(),
      label: meta.cn_name,
      options: options,
      order: meta.display_order,
      controlType: 'checkbox',
      group_name: meta.group_name,
      tips: meta.tool_tip,
      value: meta.whether_enable,
    });
  }

  async getMetas(configDatas: AppSetting[] = []) {
    if (configDatas) {
      const configs = configDatas.map((data) => {
        let controlType;
        if (!!data.template) {
          controlType = 'checkbox';
        } else {
          controlType = 'dropdown';
        }

        switch (controlType) {
          case 'dropdown':
            return this.getDropDownConfig(data);
          case 'checkbox':
            return this.getCheckboxConfig(data);
          default:
            return null;
        }
      });
      return configs.sort((a, b) => a.order - b.order);
    }
  }
}
